# !/usr/bin/env python
# encoding: utf-8
# -*- coding: utf-8 -*-
# -*- coding:utf-8 -*-
# author:darkleo
# create Date:2016/12/2
import requests
import os
from config.URL import URL


class BaiduMusic(object):

    def get_music(self,type=1,size=10,currentPage=1):
        '''
        获取百度歌曲列表方法
        :param type: 歌曲类型(默认新歌)  1-新歌榜,2-热歌榜,11-摇滚榜,12-爵士,16-流行,21-欧美金曲榜,22-经典老歌榜,23-情歌对唱榜,24-影视金曲榜,25-网络歌曲榜
        :param size:每页显示数 默认为10
        :param currentPage: 当前页 默认为第一页
        :return: 返回歌曲信息 list集合  歌曲ID,作者,歌曲名,歌词地址
        '''
        params  = {"format":"json","from":"webapp_music"}
        params['method'] = "baidu.ting.billboard.billList"
        params['type'] = type
        params['size'] = size
        params['offset'] = (currentPage-1)*size
        response = requests.get(URL.BAIDU_MUSIC_GET_URL,params=params)
        print("get music url==>", response.url)
        music_data = response.json()
        song_list = music_data.get("song_list")
        last_data = []
        for song in song_list:
            obj = {}
            obj['song_id'] = song.get("song_id")
            obj['author'] = song.get("author")
            obj['title'] = song.get("title")
            obj['lrclink'] = song.get("lrclink")
            last_data.append(obj)
        return last_data

    def get_song_url(self,song_id):
        '''
        根据歌曲的ID获取歌曲的地址
        :param song_id: 歌曲的ID
        :return: 歌曲的地址
        '''
        payload= {"format": "json", "from": "webapp_music"}
        payload['method'] = "baidu.ting.song.play"
        payload['songid'] = song_id
        response = requests.get(URL.BAIDU_MUSIC_GET_URL,params=payload)
        song_info = response.json()
        bitrate = song_info.get("bitrate")
        if bitrate:
            song_url = bitrate.get("file_link")
        print(song_url)
        return song_url

    def download_song(self,song_id,donwload_path="music",bit=128,):
        payload= {"format": "json", "from": "webapp_music"}
        payload['method'] = "baidu.ting.song.play"
        payload['songid'] = song_id
        response = requests.get(URL.BAIDU_MUSIC_GET_URL,params=payload)
        song_info = response.json()
        if not song_info['bitrate']:
            print("Not found music download address!!")
            return None
        music_bitrate = song_info['bitrate']

        file_extension = music_bitrate["file_extension"]
        download_url = music_bitrate["file_link"]
        song_file_name = str(song_id)+"."+file_extension
        response = requests.get(download_url)
        save_path = song_file_name
        if donwload_path:
            if not os.path.exists(donwload_path):
                os.mkdir(donwload_path)
            save_path = donwload_path+"/"+song_file_name
        if os.path.exists(save_path):
            print("song_id:%s exists!not download!" % song_id)
        else:
            open(save_path, "wb").write(response.content)
            print("download %s success!" % song_id)
        return os.path.abspath(save_path)


if __name__ == '__main__':
    baiduMusic = BaiduMusic()
    music_data = baiduMusic.get_music()
    print("music_data===>", music_data)
    #song_url = baiduMusic.get_song_url(276867440)
    baiduMusic.download_song(276867440, donwload_path="music")